//
//  SISSFilterChooseBaseViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/8/3.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSFilterChooseBaseViewController.h"
#import "SISSContactSearchView.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSBuildingNumberModel.h"
#import "NSBundle+PYSearchExtension.h"

@interface SISSFilterChooseBaseViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

/// 搜索历史
@property (nonatomic, strong) NSMutableArray *searchHistories;
/// 基本搜索TableView(显示历史搜索和搜索记录)
@property (nonatomic, strong) UITableView *baseSearchTableView;
/// 搜索历史记录缓存数量，默认为20
@property (nonatomic, assign) NSUInteger searchHistoriesCount;
@property (nonatomic, copy) NSString *searchHistoriesCachePath;
/// 是否显示搜索历史，默认为：YES 注意：当设置为NO时，搜索记录不缓存
@property (nonatomic, assign) BOOL showSearchHistory;

@property (weak, nonatomic) UIView *searchView;
@property (weak, nonatomic) UITextField *searchTextField;
@property (weak, nonatomic) UIButton *confirmButton;
/**
 searchDataArr
 */
//@property (copy, nonatomic) NSArray *searchDataArr;

@end

@implementation SISSFilterChooseBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.searchTextField becomeFirstResponder];
    // 是否显示搜索历史YES显示
    self.showSearchHistory = NO;
    self.searchHistoriesCount = 10;
    // 接收筛选TextField文字改变的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotificationAction:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.searchTextField becomeFirstResponder];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 收到文字改变后的筛选
- (void)textFieldTextDidChangeNotificationAction:(NSNotification *)notification {
    UITextField *textField = notification.object;
    if (textField.markedTextRange == nil) {
        NSLog(@"%@",textField.text);
        NSString *text = textField.text ? textField.text : @"";
        if (text.length > 0 && !self.isBuildingIn) {
            [self fuzzySearchHouseResourceCommunityWithKeyword:text];
        }
    }
}

#pragma mark - 加载数据
- (void)fuzzySearchHouseResourceCommunityWithKeyword:(NSString *)text {
    [kJsonRequestNetworkingManager fuzzySearchHouseResourceCommunityWithKeyword:text successBlock:^(id responseObject) {
    
        self.dataSource = responseObject[@"data"];
        self.baseSearchTableView.hidden = !self.showSearchHistory || self.dataSource.count || self.searchHistories.count == 0;
//        if (self.dataSource.count > 0) {
//            [self.searchTextField resignFirstResponder];
//        }
        [self.tableView reloadData];
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // 如果有搜索文本且显示搜索建议，h
    self.baseSearchTableView.hidden = self.searchHistories.count == 0 || !self.showSearchHistory;
    
}
#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 101) {
        // 没有搜索记录就隐藏或者隐藏搜索建议
        self.baseSearchTableView.hidden = self.searchHistories.count == 0 || !self.showSearchHistory;
        return self.searchHistories.count;
    }
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 101) {
        static NSString * const cellID = @"PYSearchHistoryCellID";
        // 创建cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.textLabel.textColor = COLOR(0x334A60);
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.backgroundColor = [UIColor clearColor];
            
            // 添加关闭按钮
            UIButton *closetButton = [[UIButton alloc] init];
            // 设置图片容器大小、图片原图居中
            closetButton.mj_size = CGSizeMake(cell.mj_h, cell.mj_h);
            [closetButton setImage:[NSBundle py_imageNamed:@"close"] forState:UIControlStateNormal];
            UIImageView *closeView = [[UIImageView alloc] initWithImage:[NSBundle py_imageNamed:@"close"]];
            [closetButton addTarget:self action:@selector(closeDidClick:) forControlEvents:UIControlEventTouchUpInside];
            closeView.contentMode = UIViewContentModeCenter;
            cell.accessoryView = closetButton;
            // 添加分割线
            UIView *lineView = [[UIView alloc] init];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.contentView addSubview:lineView];
            
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.bottom.equalTo(cell.contentView);
                make.right.equalTo(cell.contentView).offset(32);
                make.height.mas_equalTo(1);
            }];
            [cell.contentView addSubview:lineView];
        }
        
        // 设置数据
        cell.imageView.image = [NSBundle py_imageNamed:@"search_history"];
        cell.textLabel.text = self.searchHistories[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    } else {
        static NSString *reuseID = @"ID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if ( !cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            
            UIView *lineView = [[UIView alloc] init];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.contentView addSubview:lineView];
            
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.bottom.equalTo(cell.contentView);
                make.right.equalTo(cell.contentView).offset(32);
                make.height.mas_equalTo(1);
            }];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        cell.textLabel.textColor = MAIN_TEXT_COLOR;
        if (self.isBuildingIn) {
            SISSBuildingNumberModel *model = self.dataSource[indexPath.row];
            cell.textLabel.text = model.bnum;
        } else {
            cell.textLabel.text = self.dataSource[indexPath.row];
        }
        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];

    if (self.isBuildingIn) {
        SISSBuildingNumberModel *model = self.dataSource[indexPath.row];
        if (self.selectBuildingBlock) {
            self.selectBuildingBlock(model);
        }
    } else {
        [self saveSearchCacheAndRefreshViewWithSearchText:self.dataSource[indexPath.row]];
        
        if (tableView.tag == 101) { // 点击搜索历史时
            self.searchTextField.text = self.searchHistories[indexPath.row];
            [self fuzzySearchHouseResourceCommunityWithKeyword:self.searchHistories[indexPath.row]];
            return;
        } else {
            if (self.selectBlock) {
                self.selectBlock(self.dataSource[indexPath.row]);
            }
        }
    }

    [self.navigationController popViewControllerAnimated:YES];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.searchTextField resignFirstResponder];
    
}

- (void)setIsBuildingIn:(BOOL)isBuildingIn {
    _isBuildingIn = isBuildingIn;
    // 如果是楼栋选择进入就隐藏搜索历史
    self.showSearchHistory = !isBuildingIn;
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    self.searchTextField.placeholder = placeholder;
}

#pragma mark - 按钮点击事件
- (void)confirmButtonClickAction {
    if (self.isBuildingIn) {
        SISSBuildingNumberModel *model = [[SISSBuildingNumberModel alloc] init];
        if (self.searchTextField.text.length == 0) {
            [self alertWithMessage:@"请输入楼栋"];
            return;
        }
        model.bnum = self.searchTextField.text;
        self.selectBuildingBlock(model);
    } else {
        if (self.selectBlock) {
            if (self.searchTextField.text.length == 0) {
                [self alertWithMessage:@"请输入小区名"];
                return;
            }
            self.selectBlock(self.searchTextField.text);
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/// 点击x按钮
- (void)closeDidClick:(UIButton *)sender {
    // 获取当前cell
    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    // 移除搜索信息
    [self.searchHistories removeObject:cell.textLabel.text];
    // 保存搜索信息
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    // 刷新
    [self.baseSearchTableView reloadData];
}

/// 点击清空历史按钮
- (void)emptySearchHistoryDidClick {
    // 移除所有历史搜索
    [self.searchHistories removeAllObjects];
    // 移除数据缓存
    [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
    // 刷新cell
    [self.baseSearchTableView reloadData];
    
}

/** 进入搜索状态调用此方法 */
- (void)saveSearchCacheAndRefreshViewWithSearchText:(NSString *)searchText {
    
    //    if (self.removeSpaceOnSearchString) { // 移除搜索词中的空格
    //        searchText = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    //    }
    if (self.showSearchHistory && searchText.length > 0) { // 只要显示搜索历史且不为空串才会缓存
        // 先移除再刷新
        [self.searchHistories removeObject:searchText];
        [self.searchHistories insertObject:searchText atIndex:0];
        
        // 移除多余的缓存
        if (self.searchHistories.count > self.searchHistoriesCount) {
            // 移除最后一条缓存
            [self.searchHistories removeLastObject];
        }
        // 保存搜索信息
        [NSKeyedArchiver archiveRootObject:self.searchHistories toFile:self.searchHistoriesCachePath];
        
        // 刷新数据
        [self.baseSearchTableView reloadData];
    }
    
    // 处理搜索结果 跳转
    //    [self handleSearchSrSrResultShow];
}

#pragma mark - UI
- (void)setupSubviews {
    
    self.searchHistoriesCachePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"HouseSearchHistories.plist"];
    
    [super setupSubviews];
    self.tableView.tag = 100;
    
    UIView *searchView = [[UIView alloc] init];
    searchView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UITextField *textField = [[UITextField alloc] init];
    textField.backgroundColor = [UIColor whiteColor];
    textField.placeholder = self.placeholder;
    textField.delegate = self;
    [searchView addSubview:textField];
    self.searchTextField = textField;
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setBackgroundColor:MAIN_COLOR];
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
    confirmButton.layer.cornerRadius = 4;
    confirmButton.layer.masksToBounds = YES;
    [confirmButton addTarget:self action:@selector(confirmButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:confirmButton];
    self.confirmButton = confirmButton;
    
    [self.view addSubview:searchView];
   
    self.searchView = searchView;
    
    UIView *headerView = [[UIView alloc] init];
    headerView.mj_x = globelMargin;
    headerView.mj_w = SCREEN_WIDTH;
//    headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"搜索历史";
    titleLabel.font = [UIFont systemFontOfSize:13];
    titleLabel.tag = 1;
    titleLabel.textColor = SECONDARY_TEXT_COLOR;
    [titleLabel sizeToFit];
    titleLabel.mj_x = globelMargin * 2;
    titleLabel.mj_y = 0;
    [headerView addSubview:titleLabel];
    headerView.mj_h = titleLabel.mj_h;
    
    self.baseSearchTableView.tableHeaderView = headerView;
    
    // 设置底部(清除历史搜索)
    UIView *footerView = [[UIView alloc] init];
    footerView.mj_w = SCREEN_WIDTH;
    UILabel *emptySearchHistoryLabel = [[UILabel alloc] init];
    emptySearchHistoryLabel.textColor = [UIColor darkGrayColor];
    emptySearchHistoryLabel.font = [UIFont systemFontOfSize:13];
    emptySearchHistoryLabel.userInteractionEnabled = YES;
    emptySearchHistoryLabel.text = @"清除搜索历史";
    emptySearchHistoryLabel.textAlignment = NSTextAlignmentCenter;
    emptySearchHistoryLabel.mj_h = 49;
    [emptySearchHistoryLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(emptySearchHistoryDidClick)]];
    emptySearchHistoryLabel.mj_w = footerView.mj_w;
    emptySearchHistoryLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//    self.emptySearchHistoryLabel = emptySearchHistoryLabel;
    [footerView addSubview:emptySearchHistoryLabel];
    footerView.mj_h = emptySearchHistoryLabel.mj_h;
    self.baseSearchTableView.tableFooterView = footerView;
    
}

- (void)initConstraint {
    
    WeakSelf
    CGFloat margin = 8.0;
    [self.searchTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.searchView).offset(2 * margin);
        make.top.equalTo(self.searchView).offset(margin);
        make.right.equalTo(weakSelf.confirmButton.mas_left).offset(-2 * margin);
        make.bottom.equalTo(self.searchView).offset(-margin);
        make.height.mas_equalTo(4 * margin);
    }];
    
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.searchTextField);
        make.right.equalTo(weakSelf.view).offset(-2 * margin);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH * 0.15, 4 * margin));
    }];
    
    [self.searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(kTopHeight);
        make.left.right.equalTo(weakSelf.view);
        //            make.height.mas_equalTo(50);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.left.right.bottom.equalTo(weakSelf.view);
    }];
}

#pragma mark - 懒加载
- (UITableView *)baseSearchTableView {
    if (!_baseSearchTableView) {
        UITableView *baseSearchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kTopHeight + 64, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        baseSearchTableView.backgroundColor = [UIColor clearColor];
        baseSearchTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        if ([baseSearchTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)]) { // 为适配iPad
            baseSearchTableView.cellLayoutMarginsFollowReadableWidth = NO;
        }
        baseSearchTableView.tag = 101;
        baseSearchTableView.delegate = self;
        baseSearchTableView.dataSource = self;
        [self.view addSubview:baseSearchTableView];
        _baseSearchTableView = baseSearchTableView;
    }
    return _baseSearchTableView;
}

- (NSMutableArray *)searchHistories {
    if (!_searchHistories) {
        _searchHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchHistories;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
